#!/usr/bin/env python

import logging
logger = logging.getLogger('allConverging.utils')

import sys
import allconsuming.data

def main(args=None):
    if args == None:
        args = sys.argv[1:]
    return 0


if __name__ == '__main__':
    sys.exit(main())

def normalizeSynonyms(userRatings, itemMap):
    logger.debug('attempting to normalize ' + str(len(userRatings)) + ' ratings')
    results = []
    alreadySeen = {}
    i = 0
    for rating in userRatings:
        if itemMap.has_key(rating.itemNumber):
            newNumber = itemMap[rating.itemNumber][0]
            if alreadySeen.has_key((newNumber, rating.userName)):
                logger.debug('removing ' + rating.itemNumber + ' for user ' + rating.userName)
            else:
                alreadySeen[(newNumber, rating.userName)] = True
                if newNumber != rating.itemNumber:
                    logger.debug('replacing ' + rating.itemNumber + ' with ' + newNumber + ' for user ' + rating.userName)
                    rating.itemNumber = newNumber
                results.append(rating)
        else:
            results.append(rating)
    logger.debug('normalized to ' + str(len(results)) + ' ratings')
    return results

def readFromFile(fileName):
    itemMap = {}
    sets = []
    f = file(fileName, 'r')
    for line in f:
        if -1 == line.find('|'):
            continue
        (title, itemNumbers) = line.strip().split('|',1)
        sets.append(map(str.strip, itemNumbers.split(',')))

    for set in sets:
        for item in set:
            itemMap[item] = set
    return itemMap

def readFromSqlite(fileName):
    import sqlite3
    import os
    itemMap = {}
    
    conn = sqlite3.connect(os.path.abspath(fileName))
    c = conn.cursor()
    c.execute('select key, number from item_map')
    sets = {}
    for (key, number) in c:
        set = sets.get(key, [])
        set.append(number)
        sets[key] =set

    for set in sets.values():
        for v in set:
            itemMap[v] = set
        
    return itemMap

def getEquivalenceMap(fileName='equivalence.txt'):
    try:
        if fileName.endswith('.txt'):
            return readFromFile(fileName)
        else:
            return readFromSqlite(fileName)
    except:
        logger.error('unable to read equivalent items from ' + fileName + ' - ignoring', exc_info=True)
        raise

def expandSynonyms(userRatings, itemMap):
    for rating in userRatings[:]:
        print rating
        itemNumber = rating.itemNumber
        if itemMap.has_key(itemNumber):
            print 'found', itemNumber
            for mappedItemNumber in itemMap[itemNumber]:
                if mappedItemNumber == itemNumber:
                    continue
                found = False
                for r in userRatings:
                    iNumber = r.itemNumber
                    if iNumber == mappedItemNumber:
                        found = True
                        break
                if not found:
                    extra = allconsuming.data.Consumable(rating.userName)
                    extra.itemNumber = mappedItemNumber
                    extra.consumed = rating.consumed
                    extra.rating = rating.rating
                    extra.itemTitle = rating.itemTitle
                    extra.tags = rating.tags

                    logger.debug('adding ' + str(extra))
                    userRatings.append(extra)
        else:
            print 'did not find', itemNumber

    return userRatings
    
